package com.agileai.portal.controller.boxy;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.grid.Grid4boxConfigManage;
import com.agileai.portal.bizmoduler.grid.Grid4boxFieldsConfigManage;
import com.agileai.portal.driver.common.PortletVariableHelper;
import com.agileai.portal.portlets.PortletCacheManager;
import com.agileai.portal.portlets.grid.DataGridPortlet;
import com.agileai.util.StringUtil;

public class DataGridBoxyHandler extends BaseHandler{
	private static final String PopupGridParams = "PopupGridParams"; 
	
	public ViewRenderer prepareDisplay(DataParam param) {
		String gridCode = param.get("gridCode");
		String targetPage = param.get("targetPage");
		
		Grid4boxConfigManage service = lookupService(Grid4boxConfigManage.class);
		DataRow row = service.getRecord(new DataParam("gridCode",gridCode));
		
		String height = row.stringValue("HEIGHT");
		String width = row.stringValue("WIDTH");
		String pageSize = row.stringValue("PAGE_SIZE");
		String pageSizeList = row.stringValue("PAGE_SIZE_LIST");
		String customHead = row.stringValue("CUSTOM_HEAD");
		String hasClickCallBack = row.stringValue("EXISTS_CALLBACK");
		String callbackFunction = row.stringValue("CALLBACK_FUNC");
		String onloadCallback = row.stringValue("ONLOAD_CALLBACK");
		
		this.setAttribute("gridCode", gridCode);
		this.setAttribute("targetPage", targetPage);
		
		this.setAttribute("height", height);
		this.setAttribute("width", width);
		this.setAttribute("pageSize", pageSize);
		this.setAttribute("pageSizeList", pageSizeList);
		this.setAttribute("onloadCallback", onloadCallback);
		if (customHead != null){
//			customHead = customHead.replaceAll("'", "\"").replaceAll("\r\n", "");
			customHead = replaceBlank(customHead);
		}
		this.setAttribute("customHead", customHead);
		
		this.setAttribute("hasClickCallBack",Boolean.valueOf("Y".equals(hasClickCallBack)?true:false));
		this.setAttribute("callbackFunction", callbackFunction);

		Grid4boxFieldsConfigManage fieldsConfigService = lookupService(Grid4boxFieldsConfigManage.class);
		List<DataRow> fieldsConfigRecords = fieldsConfigService.findRecords(new DataParam("gridCode",gridCode));
		StringBuffer fieldsBuffer = new StringBuffer();
		StringBuffer colsBuffer = new StringBuffer();
		DataGridPortlet.buildFieldsConfig(fieldsConfigRecords,fieldsBuffer);
		DataGridPortlet.buildColsConfig(fieldsConfigRecords,colsBuffer);
		this.setAttribute("fieldsConfig", fieldsBuffer.toString());
		this.setAttribute("colsConfig", colsBuffer.toString());
	
		return new LocalRenderer(getPage());
	}

	private String replaceBlank(String str) {
		String after = "";
		if (str != null){
			Pattern p = Pattern.compile("\\r|\n");
//			System.out.println("before:" + str);
			Matcher m = p.matcher(str);
			after = m.replaceAll("");
//			System.out.println("after:" + after);
		}
		return after;
	}

	@PageAction
	public ViewRenderer popupRequest(DataParam param){
		StringBuffer responseText = new StringBuffer();
		String gridCode = param.get("gridCode");
		Grid4boxConfigManage service = lookupService(Grid4boxConfigManage.class);
		DataRow row = service.getRecord(new DataParam("gridCode",gridCode));
		
		String height = row.stringValue("HEIGHT");
		String width = row.stringValue("WIDTH");
		String title = row.stringValue("NAME");
		
		LinkedHashMap<String,String> params = new LinkedHashMap<String,String>();
		Iterator<String> iter =  param.keySet().iterator();
		while (iter.hasNext()){
			String key = iter.next();
			String value = param.get(key);
			if (key.equals("gridCode") || key.equals("targetPage") || key.equals("__randomnumber")){
				continue;				
			}
			params.put(key, value);
		}
		this.putSessionAttribute(PopupGridParams, params);
		
		responseText.append("{");
		responseText.append("\"gridCode\":\"").append(gridCode).append("\",");
		if (!StringUtil.isNullOrEmpty(height) && !StringUtil.isNullOrEmpty(width)){
			responseText.append("\"height\":\"").append(height).append("\",");
			responseText.append("\"width\":\"").append(width).append("\",");
		}
		responseText.append("\"title\":\"").append(title).append("\"}");
		
		return new AjaxRenderer(responseText.toString());
	}
	@PageAction
	public ViewRenderer retrieveJson(DataParam param){
		String gridCode = param.get("gridCode");
		String namespace = param.get("targetPage");
		if (StringUtil.isNullOrEmpty(namespace)){
			namespace = "";
		}
		else{
			namespace = StringUtil.join(namespace.split("/"),"");
			if (namespace.endsWith(".ptml")){
				namespace = namespace.substring(0,namespace.length()-5);
			}
		}
		
		Grid4boxConfigManage service = lookupService(Grid4boxConfigManage.class);
		DataRow row = service.getRecord(new DataParam("gridCode",gridCode));
		String dataURL = row.stringValue("DATA_URL");
		String defaultValueString = row.stringValue("VARIABLE_VALUES");
		defaultValueString = mergeDefaultValueString(defaultValueString);
		
		PortletVariableHelper variableHelper = new PortletVariableHelper(request,namespace,defaultValueString);
		dataURL = variableHelper.getRealDataURL(dataURL);
		
		String jsonData = "";
		try {
			jsonData = PortletCacheManager.getOnly().getCachedData("N", dataURL,"-1");	
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new AjaxRenderer(jsonData);
	}
	
	@SuppressWarnings("unchecked")
	private String mergeDefaultValueString(String defaultValueString){
		String result = defaultValueString;
		LinkedHashMap<String,String> params = (LinkedHashMap<String,String>)this.getSessionAttribute(PopupGridParams);
		if (params != null){
			String[] keyValuePairs = defaultValueString.split("&");
			for (int i=0;i < keyValuePairs.length;i++){
				String keyValuePair = keyValuePairs[i];
				String[] key8value = keyValuePair.split("=");
				if (key8value.length > 1){
					String key = key8value[0];
					if (!params.containsKey(key)){
						String value = key8value[1];
						params.put(key, value);						
					}
				}
			}
			String temp = "";
			Iterator<String> iter = params.keySet().iterator();
			while (iter.hasNext()){
				String key = iter.next();
				String value = params.get(key);
				temp = temp + key + "="+value+"&";
			}
			if (temp.endsWith("&")){
				result = temp.substring(0,temp.length()-1);
			}
		}
		
		return result;
	}
}